package gw.com.android.ui.quote2.addquote;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.dialog.BasePopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonTextWatcher;
import www.com.library.util.CommonUtils;
import www.com.library.util.JsonUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.RecycleViewDivider;
import www.com.library.view.TintImageView;
import www.com.library.view.TintTextView;

/**
 * 行情搜索界面弹层
 * @author Administrator
 *
 */
public class QuoteSearchPopWindow extends BasePopWindow {
	private EditText mEtSearch;
	private TextView mCancelBtn;
	private TintTextView mClearBtn;
	private TextView mHisView;
	private TextView mSearchView;
	private TextView mEmptyView;
	private DataItemResult mHisSearch = new DataItemResult();

	public QuoteSearchPopWindow(Activity activity, View view) {
		initPopWindow(activity, view, R.layout.dialog_quote_search,null);
	}

	@Override
	public void createPopWindow(View dialogView) {
		LinearLayout listLayout = (LinearLayout) dialogView.findViewById(R.id.list_layout);
		mEtSearch = (EditText) dialogView.findViewById(R.id.searchEditText);
		mCancelBtn = (TextView) dialogView.findViewById(R.id.cancel_btn);
		mClearBtn = (TintTextView) dialogView.findViewById(R.id.view_his_clear);
		mHisView = (TextView) dialogView.findViewById(R.id.view_his_search);
		mSearchView= (TextView) dialogView.findViewById(R.id.view_search);
		mEmptyView = (TextView) dialogView.findViewById(R.id.empty_title);
		popListView = (RecyclerView) dialogView.findViewById(R.id.pop_list);
		// 线性布局管理器
		LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
		// 设置布局管理器
		popListView.setLayoutManager(linearLayoutManager);
		popListView.addItemDecoration(new RecycleViewDivider(activity, LinearLayoutManager.VERTICAL, R.drawable.common_divider_left20_bg));
		modeListAdapter = new QuoteSearchAdapter(activity, mHisSearch);
		popListView.setAdapter(modeListAdapter);

		listLayout.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});

		mCancelBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				hidden();
				MobclickEventUtlis.MobclickEventByAccountType(activity,"ClickInput");
			}
		});

		mClearBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				AppTerminal.instance().removeAllProductHistory();
				mHisSearch.clear();
				if(null != modeListAdapter){
					((QuoteSearchAdapter)modeListAdapter).refreshSortData(mHisSearch);
					modeListAdapter.notifyDataSetChanged();
				}
				mHisView.setVisibility(View.GONE);
				mClearBtn.setVisibility(View.GONE);
				MobclickEventUtlis.MobclickEventByAccountType(activity,"ClickDeleteAll");
			}
		});

		// 监听器
		mEtSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				String key = s.toString();
				handleKeySearch(key);
			}
		});
		CommonTextWatcher.bind(mEtSearch, R.id.search_content_clean);
		mEtSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus) {
					// 此处为得到焦点时的处理内容
					MobclickEventUtlis.MobclickEventByAccountType(activity,"ClickSearch");
					PackStatis.getToService(PackStatis.EventAction.CLICKINPUT.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,null);
					showSoft(true);
				} else {
					// 此处为失去焦点时的处理内容
					showSoft(false);
				}
			}
		});

		handleKeySearch("");
	}

	/**
	 * 显示隐藏软键盘
	 * @param isShow
	 */
	private void showSoft(boolean isShow){
		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		if(isShow){
			imm.showSoftInput(mEtSearch,InputMethodManager.SHOW_FORCED);
		}else{
			imm.hideSoftInputFromWindow(mEtSearch.getWindowToken(), 0); //强制隐藏键盘
		}
	}

	// 如果key不为空，则执行搜索， 否则显示历史和热门
	private void handleKeySearch(String key) {
		if(TextUtils.isEmpty(key)) {
			mEtSearch.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimension(R.dimen.font_e));
			mSearchView.setVisibility(View.GONE);
			mEmptyView.setVisibility(View.GONE);
			getHistoryProduct();
		}else {
			mEtSearch.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimension(R.dimen.font_c));
			mHisView.setVisibility(View.GONE);
			mClearBtn.setVisibility(View.GONE);
			search(key);
			PackStatis.getToService(PackStatis.EventAction.CLICKSEARCH.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,key);
		}
	}

	/**
	 * 搜索关联
	 * @param key
	 */
	private void search(String key) {
		DataItemResult result = new DataItemResult();
		String resultStr = AppTerminal.instance().searchProductList(key);
		try {
			if(JsonUtil.isJsonData(resultStr)){
				JSONArray mArray = new JSONArray(resultStr);
				JsonUtil.toDataItemResult(result, mArray);
			}
			//设置自选标识
			for (int  i = 0 ; i < result.getDataCount(); i++){
				DataItemDetail itemDetail = result.getItem(i);
				if(null != itemDetail){
					if(DataManager.instance().isSelfPro(itemDetail.getInt(GTSConst.JSON_KEY_CODEID))){
						itemDetail.setIntValue(GTSConst.JSON_KEY_ISSELECTED,1);
					}
				}
			}
			handleSearchResult(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/*处理搜索结果*/
	private void handleSearchResult(DataItemResult data) {
		if(data.getDataCount() <= 0) {
			mSearchView.setVisibility(View.GONE);
			mEmptyView.setVisibility(View.VISIBLE);
		}else {
			mSearchView.setVisibility(View.VISIBLE);
			mEmptyView.setVisibility(View.GONE);
			String num = data.getDataCount()+"";
			SpannableString spreadPriceStr = new SpannableString(AppMain.getAppString(R.string.quote_search_result_title, num));
			AbsoluteSizeSpan mFirstSizeSpan = new AbsoluteSizeSpan(activity.getResources().getDimensionPixelSize(R.dimen.font_c_px), true);
			spreadPriceStr.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_k), 2, 2+num.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spreadPriceStr.setSpan(mFirstSizeSpan, 2, 2+num.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
			mSearchView.setText(spreadPriceStr);
		}
		if(null != modeListAdapter){
			((QuoteSearchAdapter)modeListAdapter).refreshSortData(data);
			modeListAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 获取历史搜索数据
	 */
	private void getHistoryProduct(){
		String hisResult = AppTerminal.instance().getAllProductHistory();
		try {
			if(JsonUtil.isJsonData(hisResult)){
				JSONArray mArray2 = new JSONArray(hisResult);
				mHisSearch.clear();
				JsonUtil.toDataItemResult(mHisSearch, mArray2);

				//设置自选标识
				for (int  i = 0 ; i < mHisSearch.getDataCount(); i++){
					DataItemDetail itemDetail = mHisSearch.getItem(i);
					if(null != itemDetail){
						if(DataManager.instance().isSelfPro(itemDetail.getInt(GTSConst.JSON_KEY_CODEID))){
							itemDetail.setIntValue(GTSConst.JSON_KEY_ISSELECTED,1);
						}
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if(mHisSearch.getDataCount() > 0){
			mHisView.setVisibility(View.VISIBLE);
			mClearBtn.setVisibility(View.VISIBLE);
		}else{
			mHisView.setVisibility(View.GONE);
			mClearBtn.setVisibility(View.GONE);
		}
		if(null != modeListAdapter){
			((QuoteSearchAdapter)modeListAdapter).refreshSortData(mHisSearch);
			modeListAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void show() {
		// super.show();
		if (hasShowing()) {
			return;
		}
		// 设置pop出来后，软键盘的属性，避免pop挡住软键盘，以及pop获取焦点后软键盘会自动隐藏问题
		popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//
//		// 使用该属性时，在滑动pop的时候不会自动弹出软键盘
		popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

		if (!activity.isFinishing()) {
			view = activity.getWindow().getDecorView();
			popWindow.showAtLocation(view, Gravity.FILL, 0, 0);
		}
		showSoft(false);
	}

	/**
	 * 产品搜索列表适配器
	 */
	public class QuoteSearchAdapter extends RecyclerView.Adapter {

		/** 产品布局加载器 **/
		private LayoutInflater mInflater;
		/** 上下文 **/
		private BaseActivity mOwnerAct;
		/**记录当前是否正在刷新*/
		private boolean onBind = false;
		private DataItemResult mList;

		/**
		 * 初始化界面数据
		 *
		 * @param context
		 */
		public QuoteSearchAdapter(Context context, DataItemResult mTmpList) {
			super();
			mOwnerAct = (BaseActivity) context;
			mInflater = LayoutInflater.from(context);
			mList = new DataItemResult();
			mList.appendItems(mTmpList);
		}

		/**
		 * 刷新界面排序后的数据
		 */
		public void refreshSortData(DataItemResult mTmpList){
			mList.clear();
			mList.appendItems(mTmpList);
			if(!onBind){
				notifyDataSetChanged();
			}
		}

		/**
		 * 刷新当前更新的产品报价
		 *
		 * @param codeId
		 */
		public void refreshData(int codeId) {
			if(!onBind) {
				for (int i = 0; i < mList.getDataCount(); i++) {
					DataItemDetail item = mList.getItem(i);
					if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
//				    Logger.e("QuoteListAdapter refreshData 更新操作 codeId = " + codeId);
						notifyItemChanged(i, item);
						break;
					}
				}
			}
		}

		@Override
		public int getItemCount() {
			return null == mList ? 0 : mList.getDataCount();
		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
			final DataItemDetail item = getItem(position);
			QuoteItemView viewholder = (QuoteItemView) holder;
			if (null != item) {
				viewholder.itemView.setTag(item);

				if(item.getString(GTSConst.JSON_KEY_BUYPRICE).equals("0.0") || item.getString(GTSConst.JSON_KEY_SELLPRICE).equals("0.0")){
					setEmptyView(viewholder);
					viewholder.tvProductName.setText(DataManager.instance().getPrdName(item));
					viewholder.tvProductSubName.setText(item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
				}else {
					updateViews(viewholder, item);
				}
			} else {
				setEmptyView(viewholder);
			}
		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
			onBind = true;
//		Logger.e("QuoteListAdapter position == " + position + ", "+payloads.isEmpty());
			if(payloads.isEmpty()){
				onBindViewHolder(holder, position);
			}else{
				final DataItemDetail item = (DataItemDetail) payloads.get(0);
				QuoteItemView viewholder = (QuoteItemView) holder;
				if (null != item) {
					viewholder.itemView.setTag(item);
					updateViews(viewholder, item);
				}
			}
			onBind = false;
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup convertView, int viewType) {
			View v = mInflater.inflate(R.layout.list_item_quote_new_search, convertView, false);
			return new QuoteItemView(v);
		}

		public DataItemDetail getItem(int position) {
			if (position < 0 || position >= mList.getDataCount()) {
				return null;
			}

			if(null !=  mList && null != mList.getItem(position)){
				return mList.getItem(position);
			}

			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * 更新展示界面数据，主要更新价格部分
		 *
		 * @param viewholder
		 * @param mItem 	产品对象
		 */
		public void updateViews(QuoteItemView viewholder, final DataItemDetail mItem) {
//		AppUtil.error("prdName == " + prdName);
			viewholder.tvProductName.setText(DataManager.instance().getPrdName(mItem));
			viewholder.tvProductSubName.setText(mItem.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
			//产品信息类型，是否为参考行情
			if (mItem.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || mItem.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF) {
				viewholder.tvProductType.setSelected(true);
				viewholder.tvProductType.setVisibility(View.VISIBLE);
			}else{
				viewholder.tvProductType.setVisibility(View.INVISIBLE);
			}

			if(mItem.getInt(GTSConst.JSON_KEY_ISSELECTED) == 1){
				viewholder.tvProductAdd.setImageResource(R.mipmap.a_quote_editchoose);
				viewholder.tvProductAdd.setColorValue(ColorThemeUtil.instance().color_k, ColorThemeUtil.instance().color_k);
			}else{
				viewholder.tvProductAdd.setImageResource(R.mipmap.a_quote_editadd);
				viewholder.tvProductAdd.setColorValue(ColorThemeUtil.instance().color_c, ColorThemeUtil.instance().color_c);
			}

		}

		/**
		 * 设置空数据界面
		 */
		private void setEmptyView(QuoteItemView viewHolder) {
			viewHolder.tvProductName.setText(StringUtils.NA_MSG);
			viewHolder.tvProductSubName.setText(StringUtils.NA_MSG);
			viewHolder.tvProductAdd.setVisibility(View.GONE);
			viewHolder.tvProductType.setVisibility(View.INVISIBLE);
		}

		public class QuoteItemView extends RecyclerView.ViewHolder {
			@BindView(R.id.add_view)
			public TintImageView tvProductAdd;
			@BindView(R.id.product_name)
			public TextView tvProductName;
			@BindView(R.id.product_sub_name)
			public TextView tvProductSubName;
			@BindView(R.id.product_type)
			public TextView tvProductType;

			public QuoteItemView(View convertView) {
				super(convertView);
				ButterKnife.bind(this, convertView);
			}

			@OnClick(R.id.ll_product_item)
			void onProductClick(){
				if(CommonUtils.isFastDoubleClick()){
					return;
				}
				DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
				if (null == mTickModel) {
					Logger.i("行情数据对象为空！！！");
					showErrorMsg(ConfigType.SERVER_ERROR_1021);
					return;
				}
				showSoft(false);
				AppTerminal.instance().addProductToHistory(mTickModel.getInt(GTSConst.JSON_KEY_CODEID));
				MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickResult");
				PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCT.getValue(), PackStatis.EventCategory.MARKET.getValue(),null,null);
				ActivityManager.showChartActivity(mOwnerAct, mTickModel.getInt(GTSConst.JSON_KEY_CODEID), mTickModel.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_QUOTE);
			}

			@OnClick(R.id.add_view)
			void onProductAddClick(){
				if(CommonUtils.isFastDoubleClick()){
					return;
				}
				if (!NetworkMonitor.hasNetWork()) {
					return;
				}
				DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
				if(null != mTickModel){
					if(mTickModel.getInt(GTSConst.JSON_KEY_ISSELECTED) == 0){
						mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_add_suc));
						DataManager.instance().addSelfTick(mTickModel);
						mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED,1);
						AppTerminal.instance().addProductToHistory(mTickModel.getInt(GTSConst.JSON_KEY_CODEID));
						MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickResultAdd");
					}else{
						mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_cancel_suc));
						DataManager.instance().removeSelfTick(mTickModel);
						mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED,0);
						MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickResultDelete");
					}
					RxBus.getInstance().post(GTSConst.REPLY_QUOTE_SELF, mTickModel);
					AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
					notifyDataSetChanged();
				}
			}

		}

		private void showErrorMsg(String errorId){
			final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
			dialog.show();
		}

	}

}
